#include "adcsample.h"

uint16_t adc_data[ADCSAMPLE_MAX_LEN];
__IO uint8_t adc_dma_cplt = 0;

void adcsample_init()
{
	HAL_TIM_Base_Start(&htim3);
}

uint16_t* adcsample_get_points(size_t N)
{
	size_t n;
	
	n = N > ADCSAMPLE_MAX_LEN ? ADCSAMPLE_MAX_LEN : N;
	
	HAL_ADC_Start_DMA(&hadc1, (uint32_t*)adc_data, n);
	while(adc_dma_cplt == 0);
	HAL_ADC_Stop_DMA(&hadc1);
	adc_dma_cplt = 0;
	return adc_data;
}

int16_t adcsample_find_rasing(uint16_t *points, uint16_t trig_level, size_t N)
{
	size_t i;
	
	for (i = 2; i < N-1; i++) {
		if (points[i] >= trig_level && points[i-2] <= trig_level) return i-1;
	}
	
	return -1;
}

size_t find_max_idx(uint16_t *points, size_t length)
{
	size_t max_i = 0;
	size_t i = 0;
	for (i = 0; i < length; i++) {
		if (points[i] > points[max_i]) max_i = i;
	}
	return max_i;
}

uint16_t find_max_value(uint16_t *points, size_t length)
{
	uint16_t max_val = 0;
	size_t i = 0;
	for (i = 0; i < length; i++) {
		if (points[i] > max_val) max_val = points[i];
	}
	
	return max_val;
}

uint16_t find_min_value(uint16_t *points, size_t lenght)
{
	uint16_t min_val = 65535;
	size_t i = 0;
	for (i = 0; i < lenght; i++) {
		if (points[i] < min_val) min_val = points[i];
	}
	
	return min_val;
}